package thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

//实现一个固定线程个数的线程池
class MyThreadPool{
    private BlockingQueue<Runnable> queue=null;
    public MyThreadPool(int n){
        queue=new ArrayBlockingQueue<>(100);

        for (int i = 0; i < n; i++) {
            Thread thread=new Thread(()->{
                while(true){
                    try {
                        Runnable task=queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }
}
public class Demo32 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool=new MyThreadPool(10);
        for (int i = 0; i < 100; i++) {
            int id=i;
            pool.submit(()->{
                System.out.println(Thread.currentThread().getName()+" id="+id);
            });
        }
        /*for (int i = 0; i < 200; i++) {
            int id=i;
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    System.out.println(id+"");
                }
            };
            pool.submit(runnable);
        }*/
    }
}
